package edu.whu.puppygo.controller;

import edu.whu.puppygo.base.HttpResponse;
import edu.whu.puppygo.dao.FragmentDao;
import edu.whu.puppygo.dto.VqaResultDto;
import edu.whu.puppygo.entity.Fragment;
import edu.whu.puppygo.entity.FragmentStatueEnum;
import edu.whu.puppygo.service.EmbeddingService;
import edu.whu.puppygo.service.VqaService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * @Author xinjiezhuang
 * @Date 2023-11-14
 */
@RestController
@Slf4j
@RequestMapping("/vqa")
public class VqaController {

    @Resource
    private VqaService vqaService;

    @Resource
    private FragmentDao fragmentDao;

    @Resource
    private EmbeddingService embeddingService;

    @PostMapping(value = "/send")
    public HttpResponse<String> sendMsg(String image, String text, Long fragmentId) {
        vqaService.sendMsg(image, text, fragmentId);
        return HttpResponse.success("success");
    }

    @PostMapping("/callback")
    @ApiOperation(value = "vqa结果回调，回调后请求查知识库服务")
    public HttpResponse<String> handleCallback(@Valid @RequestBody VqaResultDto resultBody) {
        log.info("这是vqa的回调函数：");
        System.out.println("resultBody" + resultBody);
        Fragment fragment = fragmentDao.findById(resultBody.getFragmentId()).orElseThrow(() -> new RuntimeException("问答不存在"));
        String answer = resultBody.getAnswer();
        fragment.setImgResult(answer);
        fragment.setStatue(FragmentStatueEnum.VQA_FINISHED);
        fragmentDao.save(fragment);
        log.info("fragment:{}", fragment);
        String text = fragment.getQuestion() + fragment.getImgResult();
        embeddingService.sendMsg(text, fragment.getId());
        return HttpResponse.success("ok");
    }
}
